<?php namespace Hdphp\Crypt;

class Crypt{
    //加密key
    private $key;

    private $iv;

    private $iv_size;
    
    public function __construct($textkey) 
    {
        
        $this->key  = pack ( 'H*',Config::get('app.key'));

        # 为 CBC 模式创建随机的初始向量
        $this->iv_size  =  mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_128 ,  MCRYPT_MODE_CBC );

        $this->iv  =  mcrypt_create_iv ( $this->iv_size ,  MCRYPT_RAND );
    }

    /**
     * 加密
     * @param  [type] $input [description]
     * @return [type]        [description]
     */
    public function encrypt($input) 
    {
       $ciphertext = mcrypt_encrypt ( MCRYPT_RIJNDAEL_128 ,  $this->key ,$input ,  MCRYPT_MODE_CBC ,  $this->iv );

        // 将初始向量附加在密文之后，以供解密时使用
        $ciphertext  =$this->iv.  $ciphertext ;
        //对密文进行 base64 编码
        return base64_encode($ciphertext );
   }

   /**
    * 解密
    * @param  [type] $input [description]
    * @return [type]        [description]
    */
   public function decrypt($input) 
   {
    $ciphertext_dec  =  base64_decode ( $input );

    # 初始向量大小，可以通过 mcrypt_get_iv_size() 来获得
     $iv_dec  =  substr ( $ciphertext_dec ,  0 ,  $this->iv_size );
    
     # 获取除初始向量外的密文
     $ciphertext_dec  =  substr ( $ciphertext_dec ,  $this->iv_size );

     # 可能需要从明文末尾移除 0
     return mcrypt_decrypt ( MCRYPT_RIJNDAEL_128 ,  $this->key ,
                                     $ciphertext_dec ,  MCRYPT_MODE_CBC ,  $iv_dec );
}

}